<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <title>知识付费</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="js/common.js"></script>
  <style>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    html, body {
      height: 100%;
      font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
      background-color: #f5f7fa;
      display: flex;
      justify-content: center;
      align-items: start;
      padding-top: 0;
    }

    .page-wrapper {
      width: 100%;
      max-width: 800px;
      padding: 20px;
      position: relative;
    }

    h2 {
      text-align: center;
      color: #333;
      margin-bottom: 10px;
    }

    .current-time {
      text-align: center;
      font-size: 14px;
      color: #666;
      margin-bottom: 20px;
    }

    .toolbar {
      position: absolute;
      top: 0;
      right: 0;
      z-index: 10;
    }

    .btn {
      padding: 8px 16px;
      background-color: #e9f0ff;
      color: #007bff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      transition: background-color 0.2s ease-in-out;
    }

    .btn:hover {
      background-color: #cdddf6;
    }

    .comment {
      background-color: #fff;
      border-left: 5px solid #007bff;
      padding: 16px 20px;
      margin-bottom: 20px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      border-radius: 8px;
      width: 100%;
      min-width: 100%;
      word-break: break-word;
      display: block;
    }

    .meta {
      display: flex;
      align-items: center;
      font-size: 13px;
      color: #666;
      margin-bottom: 8px;
    }

    .meta-left {
      font-weight: bold;
      color: #007bff;
      font-size: 15px;
      max-width: 75%;
    }

    .time {
      margin-left: auto;
      font-size: 12px;
      color: #999;
    }

    .comment-market-button,  .read-btn, .block-btn {
      margin-left: 8px;
      border: none;
      border-radius: 4px;
      padding: 2px 8px;
      cursor: pointer;
      font-size: 13px;
      transition: background-color 0.2s ease-in-out;
    }

    .comment-market-button {
      background-color: #28a745;
      color: white;
    }

    .comment-market-button:hover {
      background-color: #218838;
    }

    .read-btn {
      background-color: #e9f0ff;
      color: #007bff;
    }

    .read-btn:hover {
      background-color: #cdddf6;
    }

    /* 新增：拉黑按钮样式 */
    .block-btn {
      background-color: #ffcdd2;
      color: #f44336;
    }

    .block-btn:hover {
      background-color: #ff8a80;
    }

    .user-info {
      font-size: 12px;
      color: #999;
      margin-bottom: 10px;
    }

    .content {
      font-size: 17px;
      color: #333;
      line-height: 1.6;
      margin-bottom: 12px;
      font-weight: 500;
      min-width: 100%;
      white-space: pre-wrap;
      word-break: break-word;
      overflow-wrap: break-word;
      overflow: visible;
      display: block;
    }

    .pic-btn {
      display: inline-block;
      padding: 4px 10px;
      background-color: #e9f0ff;
      color: #007bff;
      border: 1px solid #b3d4ff;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;
      vertical-align: middle;
      transition: all 0.2s ease-in-out;
      margin-left: 3px;
    }

    .pic-btn:hover {
      background-color: #cdddf6;
      color: white;
    }

    .replies {
      margin-top: 10px;
      padding-left: 16px;
      border-left: 2px dashed #ccc;
      max-height: 300px; /* 新增：设置最大高度 */
      overflow-y: auto; /* 新增：超出部分显示滚动条 */
    }

    .reply {
      background-color: #f8f9fa;
      border-radius: 6px;
      padding: 10px 14px;
      margin-top: 8px;
      border: 1px solid #e9ecef;
      min-width: 100%;
      display: block;
    }

    .reply-text {
      font-size: 15px;
      color: #333;
      white-space: pre-wrap;
      word-break: break-word;
      overflow-wrap: break-word;
      overflow: visible;
      line-height: 1.6;
    }

    .reply-meta {
      font-size: 12px;
      color: #888;

    }

    /* 修改：调整模态框整体大小和位置 */
    .modal-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.7);
      display: none;
      justify-content: center;
      align-items: center;
      z-index: 9999;
      flex-direction: column;
    }

    .modal-pic-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr); /* 修改：调整为四列布局 */
      gap: 10px; /* 图片框之间的间距 */
      max-width: 40%; /* 修改：模态框宽度固定为屏幕的40% */
      max-height: 85vh;
      overflow-y: auto;
      background-color: #fff;
      padding: 20px;
      border-radius: 10px;
      position: relative;
    }

    .modal-pic-item {
      width: 100%;
      aspect-ratio: 1 / 1; /* 修改：固定宽高比为1:1 */
      overflow: hidden;
      border-radius: 8px; /* 修改：添加圆角效果 */
      background-color: #f1f3f5;
      display: flex;
      justify-content: center;
      align-items: center;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); /* 新增：增加阴影效果 */
    }

    .modal-pic-item img {
      width: 100%;
      height: 100%;
      object-fit: cover; /* 按比例裁剪图片 */
      display: block;
    }

    .modal-close-btn {
      top: 10px;
      right: 10px; /* 修改：关闭按钮位置调整为模态框的右上角 */
      background-color: rgba(255, 255, 255, 0.9);
      border: none;
      padding: 8px 12px;
      font-size: 20px;
      border-radius: 50%;
      cursor: pointer;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
      z-index: 10000;
      margin-top: 10px;
    }

    .container {
      position: relative;
    }

    .empty-state {
      text-align: center;
      color: #999;
      font-size: 16px;
      margin-top: 50px;
      display: block; /* 修改：默认显示 */
    }

    .empty-state i {
      font-size: 48px;
      color: #ddd;
      display: block;
      margin-bottom: 10px;
    }

    /* 修改悬浮按钮容器样式 */
    .btn-container {
      position: fixed;
      bottom: 20px;
      right: 20px;
      z-index: 9999;
      display: flex;
      flex-direction: column;
      gap: 10px; /* 按钮间距 */
    }

    /* 复用 scroll-btn 样式 */
    .scroll-btn {
      width: auto; /* 自适应宽度 */
      height: auto; /* 自适应高度 */
      background-color: #e9f0ff; /* 背景颜色与一键阅读按钮一致 */
      color: #007bff; /* 文字颜色与一键阅读按钮一致 */
      border: none;
      border-radius: 4px; /* 圆角与一键阅读按钮一致 */
      cursor: pointer;
      font-size: 14px; /* 字体大小与一键阅读按钮一致 */
      padding: 8px 16px; /* 内边距与一键阅读按钮一致 */
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); /* 阴影效果与一键阅读按钮一致 */
      transition: background-color 0.2s ease-in-out; /* 动画效果与一键阅读按钮一致 */
    }

    .scroll-btn:hover {
      background-color: #cdddf6; /* 悬停背景颜色与一键阅读按钮一致 */
    }

    /* 新增：美化设置代码模态框 */
    .modal-content {
      background-color: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      width: 520px;
      max-height: 100vh;
      /*overflow-y: auto;*/
    }

    .modal-content h3 {
      margin-bottom: 15px;
      color: #333;
    }

    /* 新增：美化搜索结果列表 */
    #searchResults {
      top: 120px; /* 距离输入框下方40px */
      left: 0;
      right: 0;
      background-color: white;
      border: 1px solid #e9ecef;
      border-radius: 6px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      z-index: 1000; /* 确保悬浮在模态框内容上方 */
    }

    #searchResults li {
      padding: 12px 16px;
      cursor: pointer;
      transition: background-color 0.2s ease;
      font-size: 14px;
      color: #333;
      border-bottom: 1px solid #f1f3f5;
    }

    #searchResults li:last-child {
      border-bottom: none;
    }

    #searchResults li:hover {
      background-color: #f8f9fa;
      transform: translateX(4px);
    }

    /* 新增：居中显示关闭按钮 */
    .modal-content .close-btn-container {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }

    /* 优化搜索代码模态框里的列表样式 */
    #selectStockResults li {
      padding: 12px 16px;
      cursor: pointer;
      transition: background-color 0.2s ease, transform 0.2s ease;
      font-size: 14px;
      color: #333;
      border-bottom: 1px solid #f1f3f5;
      background-color: #f8f9fa;
      border-radius: 4px;
      margin-bottom: 8px;
    }

    #selectStockResults {
      overflow-x: hidden; /* 新增：去除水平滚动条 */
    }

    #selectStockResults li:hover {
      background-color: #e9f0ff;
      transform: scale(1.02);
    }

    #stockCodeList li {
      background-color: #f8f9fa;
      border-radius: 4px;
      padding: 8px;
      margin-bottom: 5px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    #stockCodeList li button {
      background-color: #dc3545;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 4px 8px;
      cursor: pointer;
    }

    #stockCodeList li button:hover {
      background-color: #c82333;
    }

    /* 新增：调整价格列表样式 */
    #priceList {
      width: 100%; /* 确保列表宽度占满父容器 */
      table-layout: fixed; /* 固定表格布局 */
      word-break: keep-all; /* 防止内容换行 */
    }

    #priceList li {
      display: flex; /* 使用弹性布局 */
      justify-content: space-between; /* 均匀分布内容 */
      align-items: center; /* 垂直居中对齐 */
      padding: 10px 0; /* 增加内边距 */
      border-bottom: 1px solid #f1f3f5; /* 添加底部边框 */
    }

    /* 新增：表头样式 */
    .price-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #ccc; /* 表头底部边框 */
      font-weight: bold; /* 加粗字体 */
      color: #333; /* 字体颜色 */
    }

    /* 新增：表头字段样式 */
    .price-header span {
      flex: 1; /* 平均分配宽度 */
      text-align: center; /* 居中对齐 */
    }

    /* 修改：美化表格样式 */
    #priceTable {
      width: 100%;
      border-collapse: collapse;
      margin-top: 10px;
      max-height: 300px;
      overflow-y: auto;
      font-size: 14px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      border-radius: 8px;
      overflow: hidden;
    }

    #priceTable th, #priceTable td {
      padding: 12px 15px;
      text-align: center;
      border: 1px solid #e0e0e0;
    }

    #priceTable th {
      background-color: #f5f5f5;
      font-weight: bold;
      color: #333;
    }

    #priceTable tr:nth-child(even) {
      background-color: #f8f9fa;
    }

    /* 新增：买卖盘表格样式优化 */
    .order-table-container {
      max-height: 400px;
      overflow-y: auto;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .order-table {
      width: 100%;
      border-collapse: collapse;
      font-size: 14px;
      table-layout: fixed;
    }

    .order-table th {
      background: #f8f9fa;
      padding: 12px 15px;
      border-bottom: 2px solid #e9ecef;
      color: #495057;
      font-weight: 600;
      text-align: center;
      position: sticky;
      top: 0;
      z-index: 1;
    }

    .order-table td {
      padding: 10px 12px;
      border-bottom: 1px solid #e9ecef;
      text-align: center;
    }

    .order-table tr:nth-child(even) {
      background-color: #f8f9fa;
    }

    .order-table tr:hover {
      background-color: #f1f3f5;
    }

    /* 买盘价格样式 */
    .order-table td:nth-child(2),
    .order-table td:nth-child(6) {
      color: #dc3545; /* 红色 */
      font-weight: 500;
    }

    /* 卖盘价格样式 */
    .order-table td:nth-child(6),
    .order-table td:nth-child(10) {
      color: #28a745; /* 绿色 */
      font-weight: 500;
    }

    .order-table td:nth-child(3),
    .order-table td:nth-child(7) {
      color: #6c757d; /* 灰色 */
    }

    .order-table td:nth-child(4),
    .order-table td:nth-child(8) {
      color: #007bff; /* 蓝色 */
      font-weight: 500;
    }

    #priceTable tr:hover {
      background-color: #f1f1f1;
    }

    /* 新增：提示框样式 */
    .sort-tooltip {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 8px 16px;
      border-radius: 4px;
      font-size: 14px;
      z-index: 500000;
      opacity: 0;
      transition: opacity 0.3s ease-in-out;
      pointer-events: none;
    }

    .sort-tooltip.show {
      opacity: 1;
      z-index: 500000;
    }

    /* 新增：美化添加按钮和行情按钮的样式 */
    .add-button, .market-button {
      background-color: #007bff;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 4px 8px;
      cursor: pointer;
      font-size: 12px;
      margin-left: 8px;
      transition: background-color 0.2s ease-in-out;
    }

    .add-button:hover, .market-button:hover {
      background-color: #0056b3;
    }

    /* 新增：行情按钮的绿色样式 */
    .market-button {
      background-color: #28a745; /* 绿色背景 */
      color: white; /* 白色文字 */
    }

    #stockCodeList li .market-button {
      background-color: #28a745; /* 绿色背景 */
      color: white; /* 白色文字 */
    }

    .market-button:hover {
      background-color: #218838; /* 深绿色背景 */
    }

    /* 新增：拖拽样式 */
    .sortable-list li {
      cursor: move;
      transition: all 0.2s ease;
    }

    .sortable-list li.dragging {
      opacity: 0.5;
      background: #f5f5f5;
    }

  </style>
</head>
<body>

<div class="page-wrapper">

  <h2>知识付费</h2>

  <!-- 当前时间 -->
  <div class="current-time" id="current-time">加载中...</div>

  <!-- 工具栏：一键阅读按钮 -->

  <!-- 新增悬浮按钮容器 -->
  <div class="btn-container" id="btn-container">
    <button class="scroll-btn" id="viewPricesBtn" onclick="showPriceModal(false)">查看价格</button>
    <button class="scroll-btn" id="marketPricesBtn" onclick="showMarketPriceModal()">大盘价格</button>
    <button class="scroll-btn" id="thsTopBtn" onclick="showThsTopModal()">同花热榜</button>
    <button class="scroll-btn" id="zdDistBtn" onclick="showZdDistModal()">涨跌分布</button>
    <button class="scroll-btn" id="searchCodeBtn" onclick="showSearchCodeModal()">搜索代码</button>
    <button class="scroll-btn" id="codeSettingsBtn" onclick="showCodeSettings()">设置代码</button>
    <button class="scroll-btn" id="readAllBtn" onclick="markAllAsRead()">一键阅读</button>
    <button class="scroll-btn" id="scrollBtn" onclick="toggleScroll()">置顶置底</button>
    <button class="scroll-btn" id="futuresBtn" onclick="showFuturesModal()">股指期货</button>
  </div>

  <!-- 评论容器 -->
  <div class="container" id="comments-container"></div>
  <div class="empty-state" id="empty-state">
    <i>📚</i>
    内容持续更新中...
  </div>

</div>

<!-- 图片模态框 -->
<div class="modal-overlay" id="picModal" style="display: none;">
  <div class="modal-pic-grid" id="picGrid"></div>
  <button class="modal-close-btn" onclick="hidePicModal()">×</button>
</div>

<!-- 新增：图片详情弹出框 -->
<div class="modal-overlay" id="picDetailModal" style="display: none;" onclick="hidePicDetail()">
  <div class="modal-pic-detail" id="picDetail"></div>
</div>

<!-- 新增：设置代码模态框 -->
<div class="modal-overlay" id="codeSettingsModal" style="display: none;">
  <div class="modal-content">
    <h3>设置代码</h3>
    <div style="display: flex; gap: 10px; position: relative;">
      <input type="text" id="stockCodeInput" placeholder="请输入名称、代码、拼音搜索股票" style="padding: 8px; border: 1px solid #ccc; border-radius: 4px; flex: 1;" oninput="handleInputChange()" onkeydown="handleEnterKey(event)">
      <button onclick="searchStocksBySetting()" style="padding: 8px 16px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">搜索</button>
    </div>
    <!-- 新增：提示信息区域 -->
    <div id="alertMessage" style="margin-top: 10px; color: red; display: none;"></div>
    <!-- 新增：搜索结果列表 -->
    <ul id="searchResults" style="list-style-type: none; padding: 0; margin-top: 10px; max-height: 200px; overflow-y: auto;"></ul>
    <ul id="stockCodeList" style="list-style-type: none; padding: 0; margin-top: 10px;" class="sortable-list">
      <!-- 股票代码列表项将动态生成 -->
    </ul>
  </div>
</div>

<!-- 新增：搜索代码模态框 -->
<div class="modal-overlay" id="selectStockModal" style="display: none;">
  <div class="modal-content">
    <h3>搜索代码</h3>
    <!-- 新增：搜索区域 -->
    <div style="display: flex; gap: 10px; align-items: center; margin-bottom: 10px;">
      <input type="text" id="selectStockInput" placeholder="请输入名称、代码、拼音搜索股票" style="flex: 1; padding: 8px; border: 1px solid #ccc; border-radius: 4px;" onkeydown="handleSelectStockEnter(event)">
      <button onclick="searchStockForSelection()" style="padding: 8px 16px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">搜索</button>
    </div>
    <!-- 新增：错误提示区域 -->
    <div id="selectStockError" style="color: red; margin-bottom: 10px; display: none;"></div>
    <ul id="selectStockResults" style="list-style-type: none; padding: 0; margin-top: 10px;  overflow-y: auto;"></ul>
  </div>
</div>

<!-- 新增：查看价格模态框 -->
<div class="modal-overlay" id="priceModal" style="display: none;">
  <div class="modal-content">
    <div style="display: flex; justify-content: space-between; align-items: center;">
      <h3>实时价格</h3>
      <button onclick="resetSort()" id="resetSortBtn" class="add-button" style="margin-left: 10px;">重置排序</button>
    </div>
    <table id="priceTable">
      <thead>
      <tr>
        <th data-sort-key="name">名称</th>
        <th data-sort-key="nowPrice">现价</th>
        <th data-sort-key="zf">涨幅</th>
        <th data-sort-key="zde">涨跌额</th>
        <th data-sort-key="address">交易所</th>
      </tr>
      </thead>
      <tbody id="priceTableBody"></tbody>
    </table>
  </div>
</div>

<!-- 新增：搜索代码模态框 -->
<div class="modal-overlay" id="searchCodeModal" style="display: none;">
  <div class="modal-content" style="width: 400px; padding: 30px; text-align: center;">
    <h3>搜索代码</h3>
    <div style="display: flex; gap: 10px; align-items: center;">
      <input type="text" id="searchCodeInput" placeholder="请输入名称、代码、拼音搜索股票" style="flex: 1; padding: 8px; border: 1px solid #ccc; border-radius: 4px;" onkeydown="handleSearchCodeEnter(event)">
      <button onclick="handleSearchButtonClick()" style="padding: 8px 16px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">搜索</button>
    </div>
  </div>
</div>

<!-- 新增：详情模态框 -->
<div class="modal-overlay" id="stockDetailModal" style="display: none;">
  <div class="modal-content" style="width: 75%; padding: 20px;">
    <h3>股票详情</h3>
    <div class="tab-container">
      <button class="tab-button active" onclick="switchTab('baseData')">基础数据</button>
      <button class="tab-button" onclick="switchTab('f10')">简况F10</button>
      <button class="tab-button" onclick="switchTab('community')">社区</button>
      <button class="tab-button" onclick="switchTab('kLine')">走势</button>
    </div>
    <div class="tab-content" id="baseData" style="display: block;">
      <div class="data-grid">
      </div>
      <!-- 新增布局容器 -->
      <div class="layout-container" style="display: flex; gap: 20px; margin-top: 20px;">
        <!-- 图片容器（左侧70%） -->
        <div class="image-container" style="flex: 0 0 40%; box-shadow: 0 2px 8px rgba(0,0,0,0.1); border-radius: 8px; padding: 10px;">
          <img id="stockMinChart"
               style="width: 100%; height: auto; border-radius: 6px;"
               alt="分时走势图">
        </div>
        <!-- 表格容器（右侧30%） -->
        <div class="table-container" style="flex: 0 0 60%;">
          <div class="order-table-container">
            <table class="order-table">
              <thead>
              <tr>
                <th>操作</th><th>价格</th><th>手数</th><th>金额</th>
              </tr>
              </thead>
              <tbody id="orderTableBody">
              <!-- 数据将动态生成 -->
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
    <div class="tab-content" id="f10" style="display: none;">
      <p>暂未开发</p>
    </div>
    <div class="tab-content" id="community" style="display: none;">
      <p>暂未开发</p>
    </div>
    <!-- 新增走势选项卡内容 -->
    <div class="tab-content" id="kLine" style="display: none;">
      <iframe id="kLineIframe"
              style="width:100%;height:700px;border:none;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.1);">
      </iframe>
    </div>
  </div>
</div>

<!-- 新增：股指期货模态框 -->
<div class="modal-overlay" id="futuresModal" style="display: none;">
  <div class="modal-content" style="width: 65%; height: 85%;padding: 0px">
    <iframe id="futuresIframe" src="" style="width:100%; height:99%; border:none;"></iframe>
  </div>
</div>

<!-- 新增：同花热榜模态框 -->
<div class="modal-overlay" id="thsTopModal" style="display: none;">
  <div class="modal-content" style="width: 25%; height: 85%;padding: 0px">
    <iframe id="thsTopIframe" src="" style="width:100%; height:99%; border:none;"></iframe>
  </div>
</div>

<!-- 新增：涨跌分布模态框 -->
<div class="modal-overlay" id="zdDistModal" style="display: none;">
  <div class="modal-content" style="width: 70%; height: 80%; padding: 0px">
    <iframe id="zdDistIframe" src="thsZdStatistics.html" style="width:100%; height:100%; border:none;overflow: hidden"></iframe>
  </div>
</div>

<script>
  const API_URL = 'http://localhost:8110/common/stockComment/list';
  const POLLING_INTERVAL = 5000;

  // 前端自维护的数据副本
  let commentDataMap = {}; // { postId: { comment, replies, readStatus } }

  // 内部维护已选择的股票数据为数组格式
  let selectedStocks = [];

  // 新增：临时变量存储当前选中的单个股票
  let currentSelectedStock = null;

  function updateCurrentTime() {
    const now = new Date();
    const timeStr = now.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-');
    document.getElementById('current-time').textContent = timeStr;
  }

  function fetchDataAndMerge() {
    // 构造请求参数
    let params = {};
    // 仅筛选subscribeFlag为true的股票
    const subscribedStocks = selectedStocks.filter(stock => stock.subscribeFlag);
    if (subscribedStocks.length > 0) {
        params.codes = subscribedStocks.map(stock => stock.searchCode).join(',');
    }

    // 构造完整的请求URL
    let url = API_URL;
    if (Object.keys(params).length > 0) {
        url += '?' + new URLSearchParams(params).toString();
    }

    fetch(url)
            .then(response => {
                if (!response.ok) throw new Error(`HTTP 错误，状态码：${response.status}`);
                return response.json();
            })
            .then(data => {
                mergeAndRender(data);
            })
            .catch(error => {
                console.error('请求失败:', error);
            });
  }

  function mergeAndRender(apiDataList) {
    if (!apiDataList || apiDataList.length === 0) {
      checkEmptyState();
      return;
    }

    const currentPostIds = new Set();

    apiDataList.forEach(comment => {
      const postId = comment.post_id;
      currentPostIds.add(postId);

      if (!commentDataMap[postId]) {
        commentDataMap[postId] = {
          comment: JSON.parse(JSON.stringify(comment)),
          replies: [],
          readStatus: false
        };
      }

      // 更新主评论数据
      commentDataMap[postId].comment = JSON.parse(JSON.stringify(comment));

      // 处理回复列表
      const replyMap = {};
      (comment.reply_list || []).forEach(reply => {
        replyMap[reply.reply_id] = reply;
      });

      const existingReplyMap = {};
      commentDataMap[postId].replies.forEach(r => {
        existingReplyMap[r.reply_id] = r;
      });

      const mergedReplies = Object.values({
        ...existingReplyMap,
        ...replyMap
      });

      // 如果新增了回复，则标记为未读
      if (mergedReplies.length > commentDataMap[postId].replies.length) {
        commentDataMap[postId].readStatus = false;
      }

      commentDataMap[postId].replies = mergedReplies;
    });

    const visibleComments = [];
    for (const postId in commentDataMap) {
      const item = commentDataMap[postId];
      if (!item.readStatus && item.comment && item.comment.post_publish_time) {
        visibleComments.push(item);
      }
    }

    // 排序：最新评论置顶
    visibleComments.sort((a, b) => {
      const timeA = new Date(a.comment.post_publish_time).getTime();
      const timeB = new Date(b.comment.post_publish_time).getTime();
      return timeB - timeA;
    });

    renderComments(visibleComments);
  }

  function renderComments(comments) {
    const container = document.getElementById('comments-container');
    container.innerHTML = '';

    comments.forEach(({ comment, replies, readStatus, isBlocked }) => {
      if (readStatus || isBlocked) return; // 跳过已读或已拉黑的评论

      const commentDiv = document.createElement('div');
      commentDiv.id = `comment-${comment.post_id}`;
      commentDiv.classList.add('comment');

      // 股票名 + 阅读按钮 + 拉黑按钮 + 时间
      const meta = document.createElement('div');
      meta.className = 'meta';

      const stockNameSpan = document.createElement('span');
      stockNameSpan.className = 'meta-left';
      stockNameSpan.textContent = comment.stockName;

      // 新增：创建按钮容器
      const buttonContainer = document.createElement('div');
      buttonContainer.style.display = 'flex';
      buttonContainer.style.alignItems = 'center';
      buttonContainer.style.marginLeft = 'auto';

      // 新增：行情按钮（当存在searchCode字段时）
      var marketBtn = null;
      if (comment.searchCode) {
        marketBtn = document.createElement('button');
        marketBtn.textContent = '行情';
        marketBtn.className = 'comment-market-button';
        marketBtn.onclick = () => {
          currentSelectedStock = {
            searchCode: comment.searchCode,
            stockName: comment.stockName,
            marketName: comment.marketName
          };
          showPriceModal(true);
        };
      }

      const readBtn = document.createElement('button');
      readBtn.textContent = '阅读';
      readBtn.className = 'read-btn';
      readBtn.onclick = () => {
        commentDataMap[comment.post_id].readStatus = true;
        renderComments(Object.values(commentDataMap).filter(c => !c.readStatus && !c.isBlocked));
        checkEmptyState();
      };

      const blockBtn = document.createElement('button');
      blockBtn.textContent = '拉黑';
      blockBtn.className = 'block-btn';
      blockBtn.onclick = () => {
        commentDataMap[comment.post_id].isBlocked = true;
        renderComments(Object.values(commentDataMap).filter(c => !c.readStatus && !c.isBlocked));
        checkEmptyState();
      };

      const timeSpan = document.createElement('span');
      timeSpan.className = 'time';
      timeSpan.textContent = comment.post_publish_time;
      timeSpan.style.marginLeft = '8px';

      // 将按钮和时间放入容器
      buttonContainer.appendChild(readBtn);
      buttonContainer.appendChild(blockBtn);
      if (marketBtn) {
        buttonContainer.appendChild(marketBtn);
      }
      buttonContainer.appendChild(timeSpan);

      meta.appendChild(stockNameSpan);
      meta.appendChild(buttonContainer); // 将容器添加到meta
      commentDiv.appendChild(meta);

      // 用户信息
      const user = document.createElement('div');
      user.className = 'user-info';
      user.textContent = `作者：${comment.post_user.user_nickname}（${comment.post_user.user_age}）`;
      commentDiv.appendChild(user);

      // 正文
      const content = document.createElement('div');
      content.className = 'content';
      content.textContent = comment.post_content;
      commentDiv.appendChild(content);

      // 查看图片按钮
      if (comment.post_pic_url && comment.post_pic_url.length > 0) {
        const picBtn = document.createElement('button');
        picBtn.textContent = '查看图片';
        picBtn.className = 'pic-btn';
        picBtn.onclick = () => showPicModal(comment.post_pic_url);
        content.appendChild(picBtn);
      }

      // 回复区
      const repliesContainer = document.createElement('div');
      repliesContainer.className = 'replies';

      // 动态调整回复区域的滚动条显示
      if (replies.length > 12) {
        repliesContainer.style.maxHeight = '400px'; // 超过12条时启用滚动条
        repliesContainer.style.overflowY = 'auto';
      }

      replies.forEach(reply => {
        const replyItem = document.createElement('div');
        replyItem.className = 'reply';

        const replyText = document.createElement('div');
        replyText.className = 'reply-text';
        replyText.textContent = reply.reply_text;

        const replyMeta = document.createElement('div');
        replyMeta.className = 'reply-meta';
        replyMeta.textContent = `回复人：${reply.reply_user.user_nickname}（${reply.reply_user.user_age}）   ${reply.reply_time}`;

        replyItem.appendChild(replyText);
        replyItem.appendChild(replyMeta);
        repliesContainer.appendChild(replyItem);
      });

      commentDiv.appendChild(repliesContainer);

      container.appendChild(commentDiv);
    });

    checkEmptyState(); // 调用检查空状态函数
  }

  function checkEmptyState() {
    const container = document.getElementById('comments-container');
    const emptyState = document.getElementById('empty-state');
    emptyState.style.display = container.children.length === 0 ? 'block' : 'none'; // 修改：根据评论数量决定显示或隐藏
  }

  function markAllAsRead() {
    for (const key in commentDataMap) {
      commentDataMap[key].readStatus = true;
    }

    document.getElementById('comments-container').innerHTML = '';
    checkEmptyState();

  }

  function showPicModal(urls) {
    const grid = document.getElementById('picGrid');
    const modal = document.getElementById('picModal');
    grid.innerHTML = '';

    // 动态调整网格布局的列数
    const columns = Math.min(urls.length, 4); // 最多4列
    grid.style.gridTemplateColumns = `repeat(${columns}, 1fr)`;

    urls.forEach(url => {
      const item = document.createElement('div');
      item.className = 'modal-pic-item';
      item.innerHTML = `<img src="${url}" alt="图片">`;

      // 新增：为每张图片绑定点击事件
      item.onclick = () => showPicDetail(url);

      grid.appendChild(item);
    });

    modal.style.display = 'flex';

    // 新增：监听模态框点击事件，点击外部区域关闭模态框
    modal.onclick = (event) => {
      if (event.target === modal) {
        hidePicModal();
      }
    };
  }

  function hidePicModal() {
    const modal = document.getElementById('picModal');
    modal.style.display = 'none';
    document.getElementById('picGrid').innerHTML = '';
  }

  // 新增：显示图片详情弹出框
  function showPicDetail(url) {
    const detailModal = document.getElementById('picDetailModal');
    const detail = document.getElementById('picDetail');

    // 清空内容并设置图片
    detail.innerHTML = `<img src="${url}" alt="图片详情" style="max-width: 100%; max-height: 100%;">`;

    detailModal.style.display = 'flex';
  }

  // 新增：隐藏图片详情弹出框
  function hidePicDetail() {
    const detailModal = document.getElementById('picDetailModal');
    detailModal.style.display = 'none';
    document.getElementById('picDetail').innerHTML = '';
  }

  // 修改：设置代码按钮点击事件处理函数
  function showCodeSettings() {
    const modal = document.getElementById('codeSettingsModal');
    modal.style.display = 'flex';
    windowRemoveAllRanges();
    loadStockCodes(); // 加载已保存的股票代码
    showAlert("");

    // 新增：清空输入框并显示默认提示文案
    const input = document.getElementById("stockCodeInput");
    input.value = ""; // 清空输入框
    input.placeholder = "请输入名称、代码、拼音搜索股票"; // 显示默认提示文案

    // 修改：将单击关闭改为双击关闭
    modal.ondblclick = (event) => {
      if (event.target === modal) {
        hideCodeSettingsModal();
      }
    };
  }

  // 新增：隐藏设置代码模态框
  function hideCodeSettingsModal() {
    const modal = document.getElementById('codeSettingsModal');
    modal.style.display = 'none';
    showAlert("");
  }

  function searchStocksBySetting(){
    const code = document.getElementById("stockCodeInput").value;
    if (!code || code.length < 2) {
      showAlert("请输入至少两个字符！");
      return;
    }
    searchStocks(code);
  }

  // 修改：搜索股票函数
  function searchStocks(code) {
    document.getElementById('selectStockInput').value = code;
    fetch(`http://localhost:8110/common/stock/fuzzySearchStock?name=${encodeURIComponent(code)}`)
            .then(response => response.json())
            .then(data => {
              if (data.code === 0) {
                if (data.data.length === 0) {
                  showAlert("未找到相关股票！");
                } else {
                  showSelectStockModal(data.data);
                }
              } else {
                showAlert("接口异常，请稍后重试！");
              }
            })
            .catch(error => {
              console.error('搜索失败:', error);
              showAlert("接口异常，请稍后重试！");
            });
  }

  // 新增：显示搜索代码模态框
  function showSelectStockModal(stocks) {
    const selectStockModal = document.getElementById('selectStockModal');
    const selectStockResults = document.getElementById('selectStockResults');
    selectStockResults.innerHTML = '';

    stocks.forEach(stock => {
      const li = document.createElement('li');
      li.style.display = 'flex'; // 使用flex布局
      li.style.justifyContent = 'space-between'; // 左右对齐
      li.style.alignItems = 'center'; // 垂直居中

      // 股票文案
      const stockText = document.createTextNode(`${stock.stockName} (${stock.searchCode}) - ${stock.marketName}`);
      li.appendChild(stockText);

      // 按钮容器
      const buttonContainer = document.createElement('div');
      buttonContainer.style.display = 'flex'; // 按钮在同一行
      buttonContainer.style.gap = '8px'; // 按钮间距

      // 添加按钮
      const addButton = document.createElement('button');
      addButton.textContent = '添加';
      addButton.className = 'add-button'; // 添加样式类
      addButton.onclick = () => selectStockFromModal(stock);
      buttonContainer.appendChild(addButton);

      // 行情按钮
      const marketButton = document.createElement('button');
      marketButton.textContent = '行情';
      marketButton.className = 'market-button'; // 添加样式类
      marketButton.onclick = () => {
        currentSelectedStock = stock; // 设置当前选中的股票
        showPriceModal(true); // 打开查看价格模态框
      };
      buttonContainer.appendChild(marketButton);

      li.appendChild(buttonContainer);
      selectStockResults.appendChild(li);
    });

    selectStockModal.style.display = 'flex';

    // 修改：将单击关闭改为双击关闭
    selectStockModal.ondblclick = (event) => {
      if (event.target === selectStockModal) {
        hideSelectStockModal();
      }
    };
  }

  // 新增：隐藏搜索代码模态框
  function hideSelectStockModal() {
    const selectStockModal = document.getElementById('selectStockModal');
    selectStockModal.style.display = 'none';

    // 新增：清空输入框文本
    document.getElementById('selectStockInput').value = '';
    document.getElementById('selectStockInput').placeholder = "请输入名称、代码、拼音搜索股票";
  }

  // 新增：从搜索代码模态框中选择股票
  function selectStockFromModal(stock) {
    // 检查是否已存在
    if (selectedStocks.some(s => s.searchCode === stock.searchCode)) {
      showAlert("股票代码已存在，请勿重复添加！");
      hideSelectStockModal(); // 新增：关闭搜索代码模态框
      return;
    }
    stock.subscribeFlag = false;
    selectedStocks.push(stock); // 添加到内部维护的数据
    renderSelectedStocks(); // 统一渲染逻辑
    saveStockCodesToLocalStorage(); // 新增：保存到 localStorage
    hideSelectStockModal();
    showAlert(""); // 清空提示信息
  }

  // 新增：渲染已选择的股票列表
  function renderSelectedStocks() {
    const list = document.getElementById('stockCodeList');
    list.innerHTML = ''; // 清空现有内容
    selectedStocks.forEach(stock => {
      const li = document.createElement('li');
      li.textContent = `${stock.stockName} (${stock.searchCode}) - ${stock.marketName}`;
      li.setAttribute('data-code', stock.searchCode);
      li.setAttribute('draggable', 'true'); // 添加可拖拽属性

      // 创建按钮容器
      const buttonContainer = document.createElement('div');
      buttonContainer.style.display = 'flex'; // 按钮在同一行
      buttonContainer.style.gap = '8px'; // 按钮间距

      // 订阅按钮
      const subscribeButton = document.createElement('button');
      subscribeButton.textContent = stock.subscribeFlag ? '已订' : '待订';
      subscribeButton.className = stock.subscribeFlag ? 'market-button' : 'add-button';
      subscribeButton.onclick = () => toggleSubscribe(stock.searchCode);
      buttonContainer.appendChild(subscribeButton);

      // 删除按钮
      const deleteButton = document.createElement('button');
      deleteButton.textContent = '删除';
      deleteButton.className = 'delete-button'; // 添加样式类
      deleteButton.onclick = () => removeStockCode(stock.searchCode);
      buttonContainer.appendChild(deleteButton);

      // 行情按钮
      const marketButton = document.createElement('button');
      marketButton.textContent = '行情';
      marketButton.className = 'market-button'; // 添加样式类
      marketButton.onclick = () => {
        currentSelectedStock = stock; // 设置当前选中的股票
        showPriceModal(true); // 打开查看价格模态框
      };
      buttonContainer.appendChild(marketButton);

      // 将按钮容器添加到列表项
      li.appendChild(buttonContainer);
      list.appendChild(li);
    });
  }

  // 新增：切换订阅状态
  function toggleSubscribe(code) {
    selectedStocks = selectedStocks.map(stock => {
        if (stock.searchCode === code) {
            return {
                ...stock,
                subscribeFlag: !stock.subscribeFlag
            };
        }
        return stock;
    });
    renderSelectedStocks();
    saveStockCodesToLocalStorage();
  }

  // 修改：选择股票函数
  function selectStock(stock) {
    const list = document.getElementById('stockCodeList');
    const existingItems = Array.from(list.getElementsByTagName('li'));
    const isDuplicate = existingItems.some(item => item.getAttribute('data-code') === stock.searchCode);

    if (!isDuplicate) {
      const li = document.createElement('li');
      li.textContent = `${stock.stockName} (${stock.searchCode}) - ${stock.marketName}`;
      li.setAttribute('data-code', stock.searchCode);
      li.innerHTML += ` <button onclick="removeStockCode('${stock.searchCode}')">删除</button>`;
      list.appendChild(li);
    }

    document.getElementById("searchResults").innerHTML = '';
    document.getElementById("stockCodeInput").value = ""; // 清空输入框
    showAlert(""); // 清空提示信息
  }

  // 修改：添加股票代码函数
  function addStockCode() {
    const input = document.getElementById("stockCodeInput");
    const code = input.value.trim();
    if (!code) return;

    let stockCodes = JSON.parse(localStorage.getItem("stockCodes")) || [];
    if (stockCodes.includes(code)) {
      showAlert("股票代码已存在，请勿重复添加！");
      hideSelectStockModal();
      return;
    }

    stockCodes.push(code);
    localStorage.setItem("stockCodes", JSON.stringify(stockCodes));
    loadStockCodes();
    input.value = "";
    showAlert(""); // 清空提示信息
  }

  // 新增：加载已保存的股票代码
  function loadStockCodes() {
    let stockCodes = JSON.parse(localStorage.getItem('stockCodes')) || [];
    selectedStocks = stockCodes;
    renderSelectedStocks(); // 统一渲染逻辑
  }

  // 新增：处理输入框内容变化事件
  function handleInputChange() {
    showAlert(""); // 清空提示信息
  }

  // 新增：显示或隐藏提示信息
  function showAlert(message) {
    const alertMessage = document.getElementById("alertMessage");
    if (message) {
      alertMessage.textContent = message;
      alertMessage.style.display = "block";
    } else {
      alertMessage.style.display = "none";
    }
  }

  // 新增：处理回车键事件
  function handleEnterKey(event) {
    if (event.key === 'Enter') {
      searchStocksBySetting();
    }
  }

  // 新增：删除股票代码
  function removeStockCode(code) {
    selectedStocks = selectedStocks.filter(stock => stock.searchCode !== code); // 删除对应的数据
    renderSelectedStocks(); // 重新渲染已选择列表
    saveStockCodesToLocalStorage(); // 新增：保存到 localStorage
    showAlert(""); // 清空提示信息
  }

  // 新增：将 selectedStocks 数据保存到 localStorage
  function saveStockCodesToLocalStorage() {
    localStorage.setItem("stockCodes", JSON.stringify(selectedStocks));
  }

  // 新增：定义全局变量存储定时器ID
  let priceIntervalId;

  // 修改：showPriceModal 函数
  function showPriceModal(singleFlag) {
    const modal = document.getElementById('priceModal');
    modal.style.display = 'flex';

    windowRemoveAllRanges();

    // 新增：ESC键监听函数
    const handleEscKey = (e) => {
      if (e.key === 'Escape') {
        hidePriceModal();
      }
    };
    
    // 添加ESC键监听
    window.addEventListener('keydown', handleEscKey);

    let searchPriceParam = {};
    if (singleFlag) {
      searchPriceParam.codes = currentSelectedStock.searchCode;
    } else if (selectedStocks.length > 0) {
      searchPriceParam.codes = selectedStocks.map(stock => stock.searchCode).join(',');
    }

    // 调用接口获取价格数据
    fetchStockPrices(searchPriceParam);

    // 清除之前的定时任务
    if (priceIntervalId) {
      clearInterval(priceIntervalId);
    }

    // 每2秒更新一次价格数据
    priceIntervalId = setInterval(() => fetchStockPrices(searchPriceParam), getRefreshInterval());

    // 绑定点击事件，点击模态框外部关闭模态框
    modal.onclick = (event) => {
      if (event.target === modal) {
        hidePriceModal();
      }
    };
    
    // 在模态框关闭时移除ESC键监听
    modal.addEventListener('hide', () => {
      window.removeEventListener('keydown', handleEscKey);
    });
  }

  // 新增：大盘价格按钮点击事件处理函数
  function showMarketPriceModal() {
    const modal = document.getElementById('priceModal');
    modal.style.display = 'flex';
    windowRemoveAllRanges();

    // 新增：ESC键监听函数
    const handleEscKey = (e) => {
      if (e.key === 'Escape') {
        hidePriceModal();
      }
    };
    
    // 添加ESC键监听
    window.addEventListener('keydown', handleEscKey);

    // 固定传参
    const searchPriceParam = {
      codes: 'sh000001,sz399001,sz399006,sh000852,sh000905,sh000300,sh000688,bj899050,sh000016,hkHSTECH,hkHSI,usIXIC,sh204001'
    };

    // 调用接口获取大盘价格数据
    fetchStockPrices(searchPriceParam);

    // 清除之前的定时任务
    if (priceIntervalId) {
      clearInterval(priceIntervalId);
    }

    // 每2秒更新一次价格数据
    priceIntervalId = setInterval(() => fetchStockPrices(searchPriceParam), getRefreshInterval());

    // 绑定点击事件，点击模态框外部关闭模态框
    modal.onclick = (event) => {
      if (event.target === modal) {
        hidePriceModal();
      }
    };
    
    // 在模态框关闭时移除ESC键监听
    modal.addEventListener('hide', () => {
      window.removeEventListener('keydown', handleEscKey);
    });
}

  // 新增：显示股指期货模态框
  function showFuturesModal() {
    const modal = document.getElementById('futuresModal');
    const iframe = document.getElementById('futuresIframe');
    iframe.src = 'stockFutures.html';
    modal.style.display = 'flex';
    windowRemoveAllRanges();
    
    // 点击模态框外部关闭
    modal.onclick = (e) => {
      if (e.target === modal) {
        hideFuturesModal();
      }
    };
  }

  // 新增：隐藏股指期货模态框
  function hideFuturesModal() {
    const modal = document.getElementById('futuresModal');
    const iframe = document.getElementById('futuresIframe');
    iframe.src = ''; // 清空iframe内容
    modal.style.display = 'none';
  }

  // 新增：显示同花热榜模态框
  function showThsTopModal() {
    const modal = document.getElementById('thsTopModal');
    const iframe = document.getElementById('thsTopIframe');
    iframe.src = 'thsTop.html';
    modal.style.display = 'flex';
    windowRemoveAllRanges();
    
    // 点击模态框外部关闭
    modal.onclick = (e) => {
      if (e.target === modal) {
        hideThsTopModal();
      }
    };
  }

  // 新增：隐藏同花热榜模态框
  function hideThsTopModal() {
    const modal = document.getElementById('thsTopModal');
    const iframe = document.getElementById('thsTopIframe');
    iframe.src = ''; // 清空iframe内容
    modal.style.display = 'none';
  }

  // 新增：显示涨跌分布模态框
  function showZdDistModal() {
    const modal = document.getElementById('zdDistModal');
    const iframe = document.getElementById('zdDistIframe');
    iframe.src = 'thsZdStatistics.html';
    modal.style.display = 'flex';
    windowRemoveAllRanges();
    
    // 点击模态框外部关闭
    modal.onclick = (e) => {
      if (e.target === modal) {
        hideZdDistModal();
      }
    };

    // ESC键关闭
    window.addEventListener('keydown', handleEscKey);
    function handleEscKey(e) {
      if (e.key === 'Escape') {
        hideZdDistModal();
      }
    }
  }

  // 新增：隐藏涨跌分布模态框
  function hideZdDistModal() {
    const modal = document.getElementById('zdDistModal');
    const iframe = document.getElementById('zdDistIframe');
    iframe.src = ''; // 清空iframe内容
    modal.style.display = 'none';
  }

  // 修改：hidePriceModal 函数
  function hidePriceModal() {
    const modal = document.getElementById('priceModal');
    modal.style.display = 'none';
    // 触发自定义事件通知移除ESC监听
    modal.dispatchEvent(new Event('hide'));

    // 清除定时器
    if (priceIntervalId) {
      clearInterval(priceIntervalId);
    }

    // 新增：清空表格内容（保留表头）
    const priceTableBody = document.getElementById('priceTableBody');
    priceTableBody.innerHTML = '';
  }

  // 修改：fetchStockPrices 函数，根据调用来源决定使用 selectedStocks 或 currentSelectedStock
  function fetchStockPrices(params) {
    fetch(`http://localhost:8110/common/stock/getStockPrice?${new URLSearchParams(params).toString()}`)
            .then(response => response.json())
            .then(data => {
              if (data.code === 200) {
                // 根据当前排序规则对数据进行排序
                if (sortRules.column) {
                  data.data.sort((a, b) => {
                    const valueA = a[sortRules.column];
                    const valueB = b[sortRules.column];

                    if (sortRules.column === 'nowPrice' || sortRules.column === 'zde' || sortRules.column === 'zf') {
                      // 数值类型排序
                      return sortRules.direction === 'asc' ? parseFloat(valueA) - parseFloat(valueB) : parseFloat(valueB) - parseFloat(valueA);
                    } else {
                      // 字符串类型排序
                      return sortRules.direction === 'asc' ? valueA.localeCompare(valueB) : valueB.localeCompare(valueA);
                    }
                  });
                }

                renderPriceList(data.data);
              } else {
                console.error('获取股票价格失败:', data.message);
              }
            })
            .catch(error => {
              console.error('获取股票价格失败:', error);
            });
  }

  // 修改：渲染股票价格列表
  function renderPriceList(stockInfoList) {
    const priceTableBody = document.getElementById('priceTableBody');
    priceTableBody.innerHTML = ''; // 清空原有内容

    stockInfoList.forEach(stockInfo => {
      const row = document.createElement('tr');

      // 股票名称（支持双击打开详情模态框）
      const nameCell = document.createElement('td');
      nameCell.textContent = `${stockInfo.name} (${stockInfo.searchCode})`;
      nameCell.style.textAlign = 'center';
      nameCell.style.cursor = 'pointer';
      nameCell.onclick = () => showStockDetailModal(stockInfo);

      // 现在价格
      const nowPriceCell = document.createElement('td');
      nowPriceCell.textContent = stockInfo.nowPrice;
      nowPriceCell.style.textAlign = 'center';
      if (stockInfo.zhangFlag === 1) {
        nowPriceCell.style.color = 'red';
      } else if (stockInfo.zhangFlag === -1) {
        nowPriceCell.style.color = 'green';
      } else {
        nowPriceCell.style.color = 'black';
      }

      // 涨幅
      const zfCell = document.createElement('td'); // 将涨幅列移动到现价列后面
      zfCell.textContent = `${stockInfo.zf}%`;
      zfCell.style.textAlign = 'center';
      if (stockInfo.zhangFlag === 1) {
        zfCell.style.color = 'red';
      } else if (stockInfo.zhangFlag === -1) {
        zfCell.style.color = 'green';
      } else {
        zfCell.style.color = 'black';
      }

      // 涨跌额
      const zdeCell = document.createElement('td');
      zdeCell.textContent = stockInfo.zde;
      zdeCell.style.textAlign = 'center';
      if (stockInfo.zhangFlag === 1) {
        zdeCell.style.color = 'red';
      } else if (stockInfo.zhangFlag === -1) {
        zdeCell.style.color = 'green';
      } else {
        zdeCell.style.color = 'black';
      }

      // 交易所名称
      const addressCell = document.createElement('td');
      addressCell.textContent = stockInfo.address;
      addressCell.style.textAlign = 'center';

      row.appendChild(nameCell);
      row.appendChild(nowPriceCell);
      row.appendChild(zfCell); // 将涨幅列移动到现价列后面
      row.appendChild(zdeCell);
      row.appendChild(addressCell);

      priceTableBody.appendChild(row);
    });
  }

  // 新增：初始化表头排序功能
  function initTableSort() {
    const headers = document.querySelectorAll('#priceTable thead th');
    headers.forEach(header => {
      header.addEventListener('click', (event) => {
        const sortKey = header.getAttribute('data-sort-key');
        sortTableByColumn(sortKey, event.currentTarget); // 将当前点击的表头元素传递给排序函数
      });
    });
  }

  // 新增：维护表头排序规则的对象
  const sortRules = {
    column: null, // 当前排序的列
    direction: 'asc' // 排序方向：'asc' 或 'desc'
  };

  // 修改：根据指定字段对表格进行排序
  function sortTableByColumn(sortKey, header) {
    const tableBody = document.getElementById('priceTableBody');
    const rows = Array.from(tableBody.querySelectorAll('tr'));
    const isAscending = !header.classList.contains('desc'); // 使用传递的表头元素判断排序方向

    // 更新排序规则
    sortRules.column = sortKey;
    sortRules.direction = isAscending ? 'asc' : 'desc';

    rows.sort((a, b) => {
      const cellA = a.querySelector(`td:nth-child(${header.cellIndex + 1})`).textContent;
      const cellB = b.querySelector(`td:nth-child(${header.cellIndex + 1})`).textContent;

      if (sortKey === 'nowPrice' || sortKey === 'zde' || sortKey === 'zf') {
        // 数值类型排序
        return isAscending ? parseFloat(cellA) - parseFloat(cellB) : parseFloat(cellB) - parseFloat(cellA);
      } else {
        // 字符串类型排序
        return isAscending ? cellA.localeCompare(cellB) : cellB.localeCompare(cellA);
      }
    });

    // 清空表格并重新插入排序后的行
    tableBody.innerHTML = '';
    rows.forEach(row => tableBody.appendChild(row));

    // 切换排序方向
    header.classList.toggle('desc');

    // 显示提示框
    showSortTooltip(sortKey, isAscending);
  }

  // 新增：显示排序提示框
  function showSortTooltip(sortKey, isAscending) {
    const tooltip = document.getElementById('sortTooltip');
    
    if (!sortKey) {
      tooltip.textContent = '已重置排序';
    } else {
      const sortText = isAscending ? '升序' : '降序';
      // 根据 sortKey 映射到中文内容
      let chineseSortKey = '';
      switch (sortKey) {
        case 'name':
          chineseSortKey = '股票名称';
          break;
        case 'address':
          chineseSortKey = '交易所';
          break;
        case 'nowPrice':
          chineseSortKey = '现价';
          break;
        case 'zde':
          chineseSortKey = '涨跌额';
          break;
        case 'zf':
          chineseSortKey = '涨幅';
          break;
        default:
          chineseSortKey = sortKey; // 默认使用原始字段名
      }

      tooltip.textContent = `按 ${chineseSortKey} ${sortText}`;
    }
    
    tooltip.classList.add('show');
    setTimeout(() => {
      tooltip.classList.remove('show');
    }, 500);
  }

  // 新增：重置排序函数
  function resetSort() {
    const headers = document.querySelectorAll('#priceTable thead th');
    headers.forEach(header => {
      header.classList.remove('desc'); // 移除排序方向的类
    });
    
    // 清除排序规则
    sortRules.column = null;
    sortRules.direction = 'asc';
    
    // 重新获取当前显示的价格数据（不重新调用接口）
    const priceTableBody = document.getElementById('priceTableBody');
    const rows = Array.from(priceTableBody.querySelectorAll('tr'));
    const originalData = rows.map(row => {
      console.log(row.cells[0].textContent)
      return {
        name: row.cells[0].textContent.replace(/\s*\(.+\)/, ''),
        searchCode: row.cells[0].textContent.match(/\((.+)\)/)[1],
        nowPrice: row.cells[1].textContent,
        zf: row.cells[2].textContent.replace('%',''),
        zde: row.cells[3].textContent,
        address: row.cells[4].textContent,
        zhangFlag: getZhangFlag(row.cells[1].style.color)
      };
    });
    
    // 按照原始顺序重新渲染
    renderPriceList(originalData);
    
    // 显示提示信息
    showSortTooltip('', true);
  }

  function getZhangFlag(color) {
    if (color === 'red') return 1;
    if (color === 'green') return -1;
    return 0;
  }

  // 新增：初始化提示框
  function initSortTooltip() {
    const tooltip = document.createElement('div');
    tooltip.className = 'sort-tooltip';
    tooltip.id = 'sortTooltip';
    document.body.appendChild(tooltip);
  }

  // 修改悬浮按钮功能
  let isAtTop = true; // 初始状态为true，表示页面加载时按钮图标朝上

  function toggleScroll() {
    if (isAtTop) {
      // 滚动到底部
      window.scrollTo({
        top: document.body.scrollHeight,
        behavior: 'smooth'
      });
    } else {
      // 滚动到顶部
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    }
    updateScrollButtonIcon(); // 更新按钮图标
  }

  // 监听滚动事件，动态更新按钮状态和图标
  window.addEventListener('scroll', () => {
    const scrollPosition = window.scrollY;
    const scrollThreshold = document.body.scrollHeight / 2; // 使用页面高度的一半作为阈值

    if (scrollPosition < scrollThreshold) {
      isAtTop = true;
    } else {
      isAtTop = false;
    }

    updateScrollButtonIcon();
  });

  function updateScrollButtonIcon() {
    const scrollBtn = document.getElementById('scrollBtn');
    if (isAtTop) {
      scrollBtn.textContent = '置底'; // 将“置顶”改为“置底”
    } else {
      scrollBtn.textContent = '置顶'; // 将“置底”改为“置顶”
    }
  }

  // 新增：处理搜索代码模态框中的回车键事件
  function handleSelectStockEnter(event) {
    if (event.key === 'Enter') {
      searchStockForSelection();
    }
  }

  // 新增：搜索股票函数（针对搜索代码模态框）
  function searchStockForSelection() {
    const input = document.getElementById('selectStockInput');
    const code = input.value.trim();
    const resultsList = document.getElementById('selectStockResults');
    resultsList.innerHTML = ''; // 清空现有结果
    if(!code){
      document.getElementById('selectStockInput').placeholder = '输入不能为空，请输入正确名称、代码、拼音进行搜索';
    }


    fetch(`http://localhost:8110/common/stock/fuzzySearchStock?name=${encodeURIComponent(code)}`)
            .then(response => response.json())
            .then(data => {
              if (data.code === 0) {
                if (data.data.length === 0) {
                  showAlert("未找到相关股票！");
                } else {
                  renderSearchResults(data.data);
                }
              } else {
                showAlert("接口异常，请稍后重试！");
              }
            })
            .catch(error => {
              console.error('搜索失败:', error);
              showAlert("接口异常，请稍后重试！");
            });
  }

  // 新增：渲染搜索结果
  function renderSearchResults(stocks) {
    const resultsList = document.getElementById('selectStockResults');
    stocks.forEach(stock => {
      const li = document.createElement('li');
      li.textContent = `${stock.stockName} (${stock.searchCode}) - ${stock.marketName}`;
      li.onclick = () => selectStockFromModal(stock); // 点击结果项选择股票
      resultsList.appendChild(li);
    });
  }

  // 新增：双击股票名称打开详情模态框
  function showStockDetailModal(stockInfo) {
    const modal = document.getElementById('stockDetailModal');
    modal.style.display = 'flex';
    windowRemoveAllRanges();

    const title = document.querySelector('#stockDetailModal h3');
    title.textContent = `${stockInfo.name}-${stockInfo.searchCode}-${stockInfo.address}`;
    switchTab('baseData');

    // 绑定点击事件，点击模态框外部关闭模态框
    modal.onclick = (event) => {
      if (event.target === modal) {
        hideStockDetailModal();
      }
    };
  }

  // 新增：渲染股票详情数据
  function renderStockDetail(stock) {
    const dataGrid = document.querySelector('#stockDetailModal .data-grid');
    dataGrid.innerHTML = '';

    // 第1行
    const row1 = document.createElement('div');
    row1.className = 'data-row';

    // 第1行第1列：现价
    const item11 = document.createElement('div');
    item11.className = 'data-item';
    item11.innerHTML = `
        <div class="data-label">现价</div>
        <div class="data-value" style="color: ${formatNumberColor(stock.zhangFlag)}">
			${stock.nowPrice !== null && stock.nowPrice !== undefined ? stock.nowPrice : '-'}
		</div>
    `;
    row1.appendChild(item11);

    // 第1行第2列：昨收-开盘
    const item12 = document.createElement('div');
    item12.className = 'data-item';
    item12.innerHTML = `
        <div class="data-label">昨收-开盘</div>
        <div class="data-value">${stock.yesterdayPrice !== null && stock.yesterdayPrice !== undefined ? stock.yesterdayPrice : '-'} - ${stock.openPrice !== null && stock.openPrice !== undefined ? stock.openPrice : '-'}</div>
    `;
    row1.appendChild(item12);

    // 第1行第3列
    const item13 = document.createElement('div');
    item13.className = 'data-item';
    item13.innerHTML = `
        <div class="data-label">跌停-涨停</div>
        <div class="data-value">${stock.stopLPrice !== null && stock.stopLPrice !== undefined ? stock.stopLPrice : '-'} - ${stock.stopHPrice !== null && stock.stopHPrice !== undefined ? stock.stopHPrice : '-'}</div>
    `;
    // 第1行第4列
    const item14 = document.createElement('div');
    item14.className = 'data-item';
    item14.innerHTML = `
        <div class="data-label">最低-最高</div>
        <div class="data-value">${stock.lprice !== null && stock.lprice !== undefined ? stock.lprice : '-'} - ${stock.hprice !== null && stock.hprice !== undefined ? stock.hprice : '-'}</div>
    `;
    row1.appendChild(item14);
    row1.appendChild(item13);

    // 第2行
    const row2 = document.createElement('div');
    row2.className = 'data-row';
    const item21 = document.createElement('div');
    item21.className = 'data-item';
    item21.innerHTML = `
        <div class="data-label">涨幅</div>
		<div class="data-value" style="color: ${formatNumberColor(stock.zhangFlag)}">${stock.zf !== null && stock.zf !== undefined ? stock.zf + "%" : '-'}</div>
    `;
    row2.appendChild(item21);
    const item22 = document.createElement('div');
    item22.className = 'data-item';
    item22.innerHTML = `
        <div class="data-label">涨跌额</div>
		<div class="data-value" style="color: ${formatNumberColor(stock.zhangFlag)}">${stock.zde !== null && stock.zde !== undefined ? stock.zde  : '-'}</div>
    `;
    row2.appendChild(item22);
    const item23 = document.createElement('div');
    item23.className = 'data-item';
    item23.innerHTML = `
        <div class="data-label">均价</div>
		<div class="data-value">${stock.avgPrice !== null && stock.avgPrice !== undefined ? stock.avgPrice  : '-'}</div>
    `;
    row2.appendChild(item23);
    const item24 = document.createElement('div');
    item24.className = 'data-item';
    item24.innerHTML = `
        <div class="data-label">市值(总-流通)</div>
		<div class="data-value">
            ${formatNumberToChineseUnit(stock.marketPrice * 100000000)}  -
            ${formatNumberToChineseUnit(stock.circulationMarketPrice  * 100000000)}
        </div>
    `;
    row2.appendChild(item24);


    // 第3行
    const row3 = document.createElement('div');
    row3.className = 'data-row';
    const item31 = document.createElement('div');
    item31.className = 'data-item';
    item31.innerHTML = `
        <div class="data-label">换手率</div>
        <div class="data-value">${stock.hsl !== null && stock.hsl !== undefined ? stock.hsl + '%' : '-'}</div>
    `;
    row3.appendChild(item31);
    const item32 = document.createElement('div');
    item32.className = 'data-item';
    item32.innerHTML = `
        <div class="data-label">市净率</div>
        <div class="data-value">${stock.sjl !== null && stock.sjl !== undefined ? stock.sjl : '-'}</div>
    `;
    row3.appendChild(item32);
    const item33 = document.createElement('div');
    item33.className = 'data-item';
    item33.innerHTML = `
        <div class="data-label">市盈率(TTM-动态-静态)</div>
        <div class="data-value">
            ${stock.syl !== null && stock.syl !== undefined ? stock.syl  : '-'} -
            ${stock.sylDynamic !== null && stock.sylDynamic !== undefined ? stock.sylDynamic  : '-'} -
            ${stock.sylStatic !== null && stock.sylStatic !== undefined ? stock.sylStatic  : '-'}
        </div>
    `;
    row3.appendChild(item33);

    const item34 = document.createElement('div');
    item34.className = 'data-item';
    item34.innerHTML = `
        <div class="data-label">振幅</div>
        <div class="data-value">
            ${stock.amplitude !== null && stock.amplitude !== undefined ? stock.amplitude + '%'  : '-'}
        </div>
    `;
    row3.appendChild(item34);

    // 第4行
    const row4 = document.createElement('div');
    row4.className = 'data-row';
    const item41 = document.createElement('div');
    item41.className = 'data-item';
    item41.innerHTML = `
        <div class="data-label">成交量</div>
        <div class="data-value">${formatNumberToChineseUnit(stock.dealCount)}手</div>
    `;
    row4.appendChild(item41);
    const item42 = document.createElement('div');
    item42.className = 'data-item';
    item42.innerHTML = `
        <div class="data-label">成交额</div>
        <div class="data-value">${formatNumberToChineseUnit(stock.dealMoney * 10000)}元</div>
    `;
    row4.appendChild(item42);
    const item43 = document.createElement('div');
    item43.className = 'data-item';
    item43.innerHTML = `
        <div class="data-label">量比</div>
        <div class="data-value">${stock.lb !== null && stock.lb !== undefined ? stock.lb : '-'} </div>
    `;
    row4.appendChild(item43);

    const item44 = document.createElement('div');
    item44.className = 'data-item';
    item44.innerHTML = `
        <div class="data-label">外盘-内盘=盘差</div>
        <div class="data-value">
            ${stock.outSum !== null && stock.outSum !== undefined ? stock.outSum : '-'} -
            ${stock.innerSum !== null && stock.innerSum !== undefined ? stock.innerSum : '-'} =
            ${stock.diffSum !== null && stock.diffSum !== undefined ? stock.diffSum : '-'}
        </div>
    `;
    row4.appendChild(item44);


    dataGrid.appendChild(row1);
    dataGrid.appendChild(row2);
    dataGrid.appendChild(row3);
    dataGrid.appendChild(row4);

    // 新增买卖盘数据渲染
    const orderTableBody = document.getElementById('orderTableBody');
    orderTableBody.innerHTML = '';

    // 生成买1-买5和卖1-卖5的数据行
    for (let i = 0; i < 5; i++) {
      const row = document.createElement('tr');

      // 买盘卖盘数据
      const buyData = stock.buyLevel5List?.[i] || {};
      const sellData = stock.sellLevel5List?.[i] || {};
      row.innerHTML += `
        <td>买${i+1}<br>卖${i+1}</td>
        <td>${buyData.price || '-'}<p>${sellData.price || '-'}</p></td>
        <td>${buyData.countHm || '-'}<p>${sellData.countHm || '-'}</p></td>
        <td>${buyData.moneyHm || '-'}<p>${sellData.moneyHm || '-'}</p></td>
      `;
      orderTableBody.appendChild(row);
    }
  }

  // 新增全局变量存储详情刷新定时器ID
  let detailRefreshIntervalId = null;

  function switchTab(tabId) {
    // 停止之前的定时刷新
    if (detailRefreshIntervalId) {
      clearInterval(detailRefreshIntervalId);
      detailRefreshIntervalId = null;
    }

    const tabs = document.querySelectorAll('.tab-button');
    tabs.forEach(tab => tab.classList.remove('active'));

    const targetTab = document.getElementById(tabId);
    const allTabs = document.querySelectorAll('.tab-content');
    allTabs.forEach(tab => tab.style.display = 'none');

    document.querySelector(`.tab-button[onclick="switchTab('${tabId}')"]`).classList.add('active');
    targetTab.style.display = 'block';

    // 新增：当切换非走势选项卡时销毁iframe
    if (tabId !== 'kLine') {
      const iframe = document.getElementById('kLineIframe');
      iframe.src = ''; // 清空src停止加载
      iframe.remove(); // 移除iframe元素
      // 重新创建iframe元素避免残留
      const newIframe = document.createElement('iframe');
      newIframe.id = 'kLineIframe';
      newIframe.style = 'width:100%;height:700px;border:none;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.1);';
      document.querySelector('#kLine').appendChild(newIframe);
    }

    // 当切换到基础数据时启动定时刷新
    if (tabId === 'baseData') {
      fetchStockDetails(); // 立即刷新一次
      detailRefreshIntervalId = setInterval(fetchStockDetails, getRefreshInterval());
    }

    // 新增走势选项卡处理
    if (tabId === 'kLine') {
      const titleH3 = document.querySelector('#stockDetailModal h3');
      const stockCode = extractStockCode(titleH3.textContent);
      document.getElementById('kLineIframe').src =
              `stockKLine.html?searchCode=${stockCode}`;
    }
  }

  // 新增：封装股票详情获取逻辑
  function fetchStockDetails() {
    const titleH3 = document.querySelector('#stockDetailModal h3');
    const stockCode = extractStockCode(titleH3.textContent);
    fetch(`http://localhost:8110/common/stock/getStockPrice?codes=${stockCode}`)
            .then(response => response.json())
            .then(data => {
              if (data.code === 200 && data.data.length > 0) {
                renderStockDetail(data.data[0]);
              }
            })
            .catch(console.error);
    //给图片渲染url
    document.querySelector('#stockMinChart').src = "http://localhost:8110/common/stock/getMinImg?searchCode=" + stockCode + "&time=" + new Date().getTime();
  }

  function hideStockDetailModal() {
    const modal = document.getElementById('stockDetailModal');
    modal.style.display = 'none';

    // 停止定时刷新
    if (detailRefreshIntervalId) {
      clearInterval(detailRefreshIntervalId);
      detailRefreshIntervalId = null;
    }

    // 新增：销毁iframe及其内容
    const iframe = document.getElementById('kLineIframe');
    iframe.src = ''; // 清空src停止加载
    iframe.remove(); // 移除iframe元素
    // 重新创建iframe元素避免残留
    const newIframe = document.createElement('iframe');
    newIframe.id = 'kLineIframe';
    newIframe.style = 'width:100%;height:700px;border:none;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.1);';
    document.querySelector('#kLine').appendChild(newIframe);
  }

  // 修改：在页面加载时初始化排序功能
  window.onload = () => {
    updateCurrentTime();
    setInterval(updateCurrentTime, 1000); // 每秒更新时间
    fetchDataAndMerge(); // 首次加载
    setInterval(fetchDataAndMerge, POLLING_INTERVAL); // 定时刷新

    // 初始化按钮状态为"置顶"，文本为"置顶"
    updateScrollButtonIcon();

    // 新增：页面加载时调用 loadStockCodes 函数，确保默认股票代码渲染到模态框中
    loadStockCodes();

    // 新增：初始化表头排序功能和提示框
    initTableSort();
    initSortTooltip();
    
    // 新增：初始化拖拽排序
    initDragSort();
  };

  // 修改：调整“搜索代码”按钮功能
  document.getElementById('searchCodeBtn').onclick = () => {
    showSelectStockModal([]); // 直接展示“搜索代码”模态框
  };

  // 修改：在“搜索代码”模态框中友好展示空数据状态
  function renderSearchResults(stocks) {
    const resultsList = document.getElementById('selectStockResults');
    resultsList.innerHTML = ''; // 清空现有结果

    if (stocks.length === 0) {
      const emptyMessage = document.createElement('li');
      emptyMessage.textContent = '暂无数据';
      emptyMessage.style.color = '#999';
      emptyMessage.style.textAlign = 'center';
      emptyMessage.style.padding = '10px';
      resultsList.appendChild(emptyMessage);
      return;
    }

    stocks.forEach(stock => {
      const li = document.createElement('li');
      li.style.display = 'flex'; // 使用flex布局
      li.style.justifyContent = 'space-between'; // 左右对齐
      li.style.alignItems = 'center'; // 垂直居中

      // 股票文案
      const stockText = document.createTextNode(`${stock.stockName} (${stock.searchCode}) - ${stock.marketName}`);
      li.appendChild(stockText);

      // 按钮容器
      const buttonContainer = document.createElement('div');
      buttonContainer.style.display = 'flex'; // 按钮在同一行
      buttonContainer.style.gap = '8px'; // 按钮间距

      // 添加按钮
      const addButton = document.createElement('button');
      addButton.textContent = '添加';
      addButton.className = 'add-button'; // 添加样式类
      addButton.onclick = () => selectStockFromModal(stock);
      buttonContainer.appendChild(addButton);

      // 行情按钮
      const marketButton = document.createElement('button');
      marketButton.textContent = '行情';
      marketButton.className = 'market-button'; // 添加样式类
      marketButton.onclick = () => {
        currentSelectedStock = stock; // 设置当前选中的股票
        showPriceModal(true); // 打开查看价格模态框
      };
      buttonContainer.appendChild(marketButton);

      li.appendChild(buttonContainer);
      resultsList.appendChild(li);
    });
  }

  // 新增：选项卡样式
  const style = document.createElement('style');
  style.innerHTML = `
    .tab-container {
      display: flex;
      margin-bottom: 20px;
    }
    .tab-button {
      padding: 8px 16px;
      background-color: #f5f5f5;
      border: 1px solid #ddd;
      cursor: pointer;
      margin-right: 5px;
      border-radius: 4px;
    }
    .tab-button.active {
      background-color: #007bff;
      color: white;
      border-color: #007bff;
    }
    .tab-content {
      padding: 15px;
    }
    .data-grid {
      display: flex;
      flex-wrap: wrap;
	  justify-content: flex-start;
    }
    .data-row {
      display: flex;
      width: 100%;
      margin-bottom: 10px;
    }
    .data-item {
      display: flex;
      flex-direction: column;
      margin-right: 10px;
	  width: calc(25% - 10px);
    }
	/* 清除每行最后一个元素的右边距 */
	.data-item:nth-child(4n) {
	  margin-right: 0;
	}
    .data-label {
      font-size: 14px;
      color: #999;
      margin-bottom: 5px;
    }
    .data-value {
      font-size: 16px;
      font-weight: bold;
    }
  `;
  document.head.appendChild(style);

  // 新增：初始化拖拽排序功能
  function initDragSort() {
    const list = document.getElementById('stockCodeList');
    if (!list) return;

    list.addEventListener('dragstart', (e) => {
      if (e.target.tagName === 'LI') {
        e.dataTransfer.setData('text/plain', e.target.dataset.code);
        e.target.classList.add('dragging');
      }
    });

    list.addEventListener('dragend', (e) => {
      if (e.target.tagName === 'LI') {
        e.target.classList.remove('dragging');
      }
    });

    list.addEventListener('dragover', (e) => {
      e.preventDefault();
      const draggingItem = document.querySelector('.dragging');
      if (!draggingItem) return;

      const afterElement = getDragAfterElement(list, e.clientY);
      if (afterElement) {
        list.insertBefore(draggingItem, afterElement);
      } else {
        list.appendChild(draggingItem);
      }
    });

    // 拖拽结束时更新数据顺序
    list.addEventListener('dragend', () => {
      updateSelectedStocksOrder();
    });
  }

  // 新增：获取拖拽后元素位置
  function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('li:not(.dragging)')];

    return draggableElements.reduce((closest, child) => {
      const box = child.getBoundingClientRect();
      const offset = y - box.top - box.height / 2;
      if (offset < 0 && offset > closest.offset) {
        return { element: child, offset: offset };
      } else {
        return closest;
      }
    }, { element: null, offset: Number.NEGATIVE_INFINITY }).element;
  }

  // 新增：更新选中股票顺序
  function updateSelectedStocksOrder() {
    const list = document.getElementById('stockCodeList');
    const newOrder = Array.from(list.querySelectorAll('li')).map(li => li.dataset.code);
    
    selectedStocks.sort((a, b) => {
      return newOrder.indexOf(a.searchCode) - newOrder.indexOf(b.searchCode);
    });
    
    saveStockCodesToLocalStorage();
  }

  window.addEventListener('keydown', function(event) {
    // 检查是否按下了空格键
    if (event.code === 'Space') {
      // 阻止空格键的默认行为（页面滚动）
      event.preventDefault();

      // 获取第一个评论元素
      const firstComment = document.querySelector('.comment');
      if (firstComment) {
        // 查找第一个评论的阅读按钮并点击
        const readBtn = firstComment.querySelector('.read-btn');
        if (readBtn) {
          readBtn.click();
          showTip("已关闭第一条评论")
        }
      }
    }
  });

</script>
</body>
</html>